<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<script language="JavaScript">
    function test() {
        var a = document.getElementsByTagName("p");
        for(var i=0;i<a.length;i++){
            a[i].onclick=function () {
                alert(i);
            }
        }
    }
</script>
<body onload="test()">
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
</body>
</html>